#pragma once
#include <iostream>
#include <unordered_map>
#include <fstream>
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace LogModule;

const std::string default_path = "./dictionary.txt";
const std::string sep = ": ";
class Dict
{
public:
    Dict(const std::string& path = default_path)
    :_path(path)
    {
        
    }
    bool Load()
    {
        std::ifstream in(_path);
        if(!in.is_open())
        {
            LOG(LogLevel::DEBUG) << "打开字典" << default_path << "错误";
            return false;
        }
        std::string line;
        while(std::getline(in, line))
        {
            auto pos = line.find(sep);
            if(pos == std::string::npos)
            {
                LOG(LogLevel::DEBUG) << "解析" << line << "失败";
                continue;
            }
            std::string chinese = line.substr(pos + sep.size());
            std::string english = line.substr(0, pos);
            if(chinese.empty() || english.empty())
            {
                LOG(LogLevel::DEBUG) << "内容无效: " << line;
            }
            _dict[english] = chinese;
            LOG(LogLevel::DEBUG) << "成功导入: " << line;
            
        }
        return true;
    }

    std::string Translate(const std::string& word, Inet_Addr& client)
    {
        auto e = _dict.find(word);
        if(e == _dict.end())
        {
            LOG(LogLevel::DEBUG) << "[进入了翻译模块" << client.IP() << ":" << client.Port() << "]# " << word << " -> " << "None";
            return "None";
        }
        LOG(LogLevel::DEBUG) << "[进入了翻译模块" << client.IP() << ":" << client.Port() << "]# " << word << " -> " << e->second;
        return e->second;
    }
    ~Dict()
    {

    }
private:
    std::string _path;
    std::unordered_map<std::string, std::string> _dict;
};